<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    title="批量设置权限所属人"
    @ok="handleSubmit"
    @cancel="handleClose"
  >
    <BasicTable @register="registerTable">
      <template #tableTitle>
        <div class="table-title">数据列表</div>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.componentType === 'switch'">
          <a-switch
            v-model:checked="record[column.dataIndex]"
            :unCheckedValue="0"
            :checkedValue="1"
            :disabled="true"
          />
        </template>
        <template v-if="column.componentType === 'picker-color'">
          <ColorPicker v-model:value="record[column.dataIndex]" :disabled="true" />
        </template>
        <template v-if="column.componentType === 'money-chinese'">
          {{
            !isNaN(record[column.dataIndex]) && record[column.dataIndex] !== null
              ? nzhcn.encodeB(record[column.dataIndex]) + '元'
              : ''
          }}
        </template>
      </template>
      <template #toolbar>
        <SelectUser
          class="select-box"
          :selectedIds="state.userIds"
          :multiple="false"
          @change="getRuleUserIds"
          @changeNames="getRuleUserNames"
        >
          <a-button type="primary"> 设置权限所属人 </a-button>
        </SelectUser>
      </template>
    </BasicTable>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { reactive } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicTable, useTable, BasicColumn } from '/@/components/Table';
  import { cloneDeep } from 'lodash-es';
  import { isFunction } from '/@/utils/is';
  import { SelectUser } from '/@/components/SelectOrganizational/index';
  import { getAllUserList } from '/@/api/system/user';
  import nzhcn from 'nzh/cn';

  const emit = defineEmits(['success', 'register']);

  const state = reactive({
    rowKey: '',
    dataSource: [] as any[],
    columns: [] as BasicColumn[],
    userIds: [],
    setDataAuthApi: null as any,
    apiParams: null,
    ruleUserIdName: 'ruleUserId',
  });

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    state.rowKey = data.rowKey;
    state.columns = cloneDeep(data.columns);
    state.dataSource = cloneDeep(data.dataSource);
    state.setDataAuthApi = data.setDataAuthApi;
    state.apiParams = data.params;
    state.ruleUserIdName = !!data.isCustomForm ? 'rule_user_id' : 'ruleUserId';

    setModalProps({
      destroyOnClose: true,
      maskClosable: false,
      fixedHeight: true,
      width: 800,
    });
    if (state.columns?.length && state.columns[0].dataIndex !== state.ruleUserIdName) {
      state.columns.unshift({
        dataIndex: state.ruleUserIdName,
        title: '当前权限人',
      });
    }

    const userInfo = await getAllUserList();

    state.dataSource.map((item) => {
      if (item[state.ruleUserIdName]) {
        const userIdsArr = item[state.ruleUserIdName].split(',');
        const userNamesArr = [] as string[];
        userInfo.map((user) => {
          if (userIdsArr.includes(user.id)) {
            userNamesArr.push(user.name);
          }
        });
        item[state.ruleUserIdName] = userNamesArr.join(',');
      }
    });
    setTableData(state.dataSource);
    setColumns(state.columns);
  });

  const [registerTable, { setTableData, setColumns }] = useTable({
    rowKey: state.rowKey,
    columns: state.columns,
    dataSource: state.dataSource,
    pagination: false,
  });

  async function handleSubmit() {
    const params = {
      userIdList: state.userIds,
      dataIdList: state.dataSource.map((x) => x[state.rowKey]),
    };
    if (isFunction(state.setDataAuthApi)) {
      !!state.apiParams
        ? await state.setDataAuthApi(state.apiParams, params)
        : await state.setDataAuthApi(params);
    }
    closeModal();
    emit('success');
    state.userIds = [];
  }

  function handleClose() {
    state.userIds = [];
  }

  function getRuleUserIds(ids) {
    state.userIds = ids;
  }

  function getRuleUserNames(names) {
    state.dataSource.map((item) => {
      item[state.ruleUserIdName] = names;
    });
    setTableData(state.dataSource);
  }
</script>
<style lange="less" scoped>
  .select-box {
    text-align: right;
    width: auto !important;
  }

  .table-title {
    font-size: 16px;
    line-height: 20px;
    padding-left: 6px;
    border-left: 6px solid #5e95ff;
  }
</style>
